let fla = 0;  // 标识位，用于确定当点击导航栏上的个人名字时是隐藏个人菜单还是显示
let cookieKey = "LIANLISESSIONID20220603";
let WType = 0;  // 工单类型标识，1 表示返修工单，2 表示维修工单
let SourceUrl = "";

// 使用正则验证用书输入的手机号格式是否正确
function isPhone(value) {
    var mobile = /^(13[0-9]{9})|(18[0-9]{9})|(14[0-9]{9})|(17[0-9]{9})|(15[0-9]{9})$/;
    if (value === "" || value.length !== 11 || !mobile.test(value)) {
        return false
    } else {
        return true
    }
}

// mobileLogin 登录按钮
function mobileLogin() {
    $(".login_send_con").css("display", "block");
}

// loginBtn 登录提交按钮
function loginBtn(val) {
    var phoneName = $("input[name='phoneName']").val();
    if (phoneName === "") {
        $("#login_tishi").css("display", "block").empty().html("登录账号不允许为空请重新填写~!").delay(6000).fadeOut();
    }
    if (!isPhone(phoneName)) {
        $("#login_tishi").css("display", "block").empty().html("抱歉！您输入的联系方式格式有误，请重新填写，谢谢!").delay(6000).fadeOut();
        return
    }
    $.ajax({
        type: "POST",
        url: "/login",
        dataType: "json",
        data: {
            "username": phoneName,
        },
        success: function (dat) {
            if (dat["success"] !== "") {
                window.location.href = SourceUrl;
            }
            if (dat["errMsg"]) {
                $("#login_tishi").css("display", "block").empty().html(dat["errMsg"]).delay(6000).fadeOut();
            }
        },
    });
}

// phoneRegis 注册按钮
function phoneRegis() {
    $(".regis_send_con").css("display", "block");
    $(".login_send_con").css("display", "none");
}

// phoneLogin 注册返回登录界面
function phoneLogin() {
    $(".login_send_con").css("display", "block");
    $(".regis_send_con").css("display", "none");
}

// regisBtn 注册提交按钮
function regisBtn(val) {
    var username = $("input[name='mobileUsername']").val();
    var phone = $("input[name='mobilePhone']").val();
    if (!isPhone(phone)) {
        $("#regis_tishi").css("display", "block").empty().html("抱歉！您输入的联系方式格式有误，请重新填写，谢谢!").delay(6000).fadeOut();
        return
    }
    $.ajax({
        type: "POST",
        url: "/registry",
        data: {
            "username": username,
            "phone": phone,
        },
        success: function (dat) {
            if (dat["success"]) {
                $(".regis_send_con").css("display", "none");
                $(".login_send_con").css("display", "block");
            }
            if (dat["errMsg"]) {
                $("#regis_tishi").css("display", "block").empty().html(dat["errMsg"]).delay(6000).fadeOut();
            }
        },
    });
}

// 点击用户名显示隐藏个人菜单
function showHideMenu() {
    if (fla === 0) {
        $(".userMenuPanel").css("display", "block");
        fla = fla + 1;
    } else {
        $(".userMenuPanel").css("display", "none");
        fla = fla - 1;
    }
}

// cLogout 退出登录按钮事件
function cLogout() {
    $.ajax({
        type: "GET",
        url: "/cLogout",
        dataType: "json",
        data: {},
        success: (ret) => {
            alert(ret["success"])
            if (ret["success"] !== "") {
                $.cookie("LIANLISESSIONID20220603", null);
                window.location.href = SourceUrl;
            }
        }
    });
}

// 创建工单按钮
function createWorkBth() {
    $(".work_info").css("display", "block");
}

// 监听下拉选择框
$(() => {
    // 记录源地址
    SourceUrl = window.location.href;
    // 监听销售下拉选择框事件
    $("#saleAdr").change(() => {
        if ($('#saleAdr').val() !== "") {
            $(".addrShow > strong").empty().text($('#saleAdr').val().split("-")[1]);
            $(".address").css("display", "block");
        } else {
            $(".address").css("display", "none");
        }
    });

    // 监听省份下拉选择框事件
    $("#province").change(() => {
        if ($('#province').val() !== "") {
            $.ajax({
                type: "GET",
                url: "/getCityDat",
                dataType: "json",
                data: {"pro_id": $('#province').val().split("-")[0]},
                success: (ret) => {
                    // getAjaxFunc("/getCityDat", {"pro_id": $('#province').val().split("-")[0]}, getCallBackFunc)
                    if (ret["success"]) {
                        var cht = `<option value=""></option>`;
                        for (var city in ret["success"]) {
                            cht += `
                            <option value="` + ret["success"][city]["CityId"] + "-" + ret["success"][city]["CityName"] + `">`
                                + ret["success"][city]["CityName"] + `
                            </option>
                        `
                        }
                        $("#city").empty().append(cht);
                    } else {
                        alert(ret["errMsg"]);
                    }
                }
            });
        }
    });
});

// 选择工单类型
function chooseWType(val) {
    switch ($(val).text()) {
        case "返修工单":
            WType = 1;
            break;
        case "维修工单":
            WType = 2;
            break;
    }
}

// addAddr 添加地址按钮
function add_address() {
    // 发起请求获取省份数据
    $.ajax({
        type: "GET",
        url: "/getProvinceDat",
        dataType: "json",
        data: {},
        success: (ret) => {
            if (ret["success"] !== "") {
                var ht = `<option value=""></option>`;
                for (var i in ret["success"]) {
                    ht += `
                        <option value="` + ret["success"][i]["ProId"] + "-" + ret["success"][i]["ProName"] + `">`
                        + ret["success"][i]["ProName"] + `
                    </option>
                    `
                }
                $("#province").empty().append(ht);
            } else {
                alert(ret["errMsg"]);
            }
        }
    });
    $(".address_send_con").css("display", "block");
}

// add_addrBtn 添加地址弹框提交按钮
function add_addrBtn(val) {
    switch ($(val).text()) {
        case "确认":
            // 获取数据，发起 post 请求
            var userInfo = ""
            var userName = $("#username").val();
            if (userName === "") {
                alert("收货人姓名不允许留空，请重新填写，谢谢!");
                return;
            }
            var province = $("#province").val();
            if (province === "") {
                alert("添加的地址省份不允许留空，请重新选择，谢谢!");
                return;
            }
            var city = $("#city").val();
            if (city === "") {
                alert("添加的地址城市不允许留空，请重新选择，谢谢!");
                return;
            }
            var userAddr = $("#userAddr").val();
            if (userAddr === "") {
                alert("收货人地址不允许留空，请重新填写，谢谢!");
                return;
            }
            var phone = $("#phone").val();
            if (phone === "") {
                alert("收货人联系方式不允许留空，请重新填写，谢谢!");
                return;
            }
            if (!isPhone(phone)) {
                alert("抱歉！您输入的联系方式格式有误，请重新填写，谢谢!");
                return
            }
            userInfo = userName + "." + province.split("-")[1] + "." + city.split("-")[1] + "." + userAddr + "." + phone;
            $.ajax({
                type: "POST",
                url: "/insertAddrToSql",
                dataType: "json",
                data: {"addr": userInfo, "option": $(val).text()},
                success: (dat) => {
                    if (dat["success"] !== "") {
                        // 添加成功隐藏添加地址页面，并清空刚刚添加的地址信息
                        $("input[name='mobileUsername']").val("");
                        $("input[name='mobilePhone']").val("");
                        $("#mobileSale").val("");
                        window.location.href = SourceUrl;
                    } else {
                        alert(dat["errMsg"]);
                    }
                }
            });
            break;
        case "取消":
            $(".address_send_con").css("display", "none");
            break;
    }
}

// 提交工单按钮
function submit_btn() {
    // 获取各种数据 发起 post 请求
    var materId = $("#materId").text().split(":")[1]
    if (WType === 0) {
        alert("您尚未选择工单类型，请返回重新选择~！");
        return;
    }
    var userAddr = $("#addr").text()
    if (userAddr === "") {
        alert("您的返回地址为空，请返回添加~！");
        return;
    }
    var expressName = $("#expressName").val()
    if (expressName === "") {
        alert("发货的物流名称不允许为空，请返回重新选择~！");
        return;
    }
    var expressNumber = $("#expressNumber").val()
    if (expressNumber === "") {
        alert("发货的物流单号不允许为空，请返回重新填写~！");
        return;
    }
    var proDesc = $("#proDesc").val();
    if (proDesc === "") {
        alert("问题原因不允许为空，请返回重新填写~！");
        return;
    }
    // TODO 如果工单类型是服务工单则在提交按钮处提示该工单需要收费，请后续在我的工单页面查看维修价格
    var data = {
        "materId": materId,
        "WType": WType,
        "userAddr": userAddr,
        "expressName": expressName,
        "expressNumber": expressNumber,
        "proDesc": proDesc
    }
    $.ajax({
        type: "POST",
        url: "/verify/createOrder",
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify(data),
        success: (ret) => {
            if (ret["success"] !== "") {
                alert("创建工单成功~！");
                window.location.href = SourceUrl;
            } else {
                alert(ret["errMsg"]);
            }
        }
    });
}

// 我的工单按钮事件
function myWorkOder() {
    $(".product,.userMenuPanel").css("display", "none");
    $(".myOrder").css("display", "block");
    fla = fla - 1;
}

// 工单类型选择按钮事件
function chooseMenu(val) {
    switch ($(val).text()) {
        case "维修工单":
            getAjaxRequest($(val).text(), {"searchType": "维修工单"}, getAjaxRequestCallBack);
            break;
        case "返修工单":
            getAjaxRequest($(val).text(), {"searchType": "返修工单"}, getAjaxRequestCallBack);
            break;
        default:
            alert("非法操作~!");
    }
}

// 搜索按钮事件
function searchBtn(val) {
    var searchInput = $("input[name='search']");
    if (searchInput.val() === "") {
        alert("搜索内容不允许为空~!");
        return;
    }
    getAjaxRequest($(val).text(), {"searchType": searchInput.val()}, getAjaxRequestCallBack);
    searchInput.val("");
}

// 返回按钮事件
function retBtn() {
    window.location.href = SourceUrl;
}

// 公共 Get 请求
function getAjaxRequest(retType, msg, callBack) {
    $.ajax({
        type: "GET",
        url: "/getWorkOrderDat",
        dataType: "json",
        data: msg,
        success: (dat) => {
            callBack(retType, dat);
        }
    });
}

// 公共 GET 请求回调函数
function getAjaxRequestCallBack(retType, dat) {
    console.log(dat["success"]);
    if (dat["success"] !== "") {
        var html = ``
        if (dat["dataLen"] <= 0) {
            html = ``;
            html += `<span>您还没有创建该类型工单......~！</span>`
            $('.search_exhibit').css("display", "none");
            $(".noneTishi").css("display", "block").empty().append(html);
            return;
        }
        html = ``;
        for (var mater in dat["success"]) {
            html += `
                    <tr>
                        <td style="display: none">` + dat["success"][mater]["pay_id"] + `</td>
                        <td>` + dat["success"][mater]["mname"] + `</td>
                        <td>` + dat["success"][mater]["create_date"] + `</td>
                        <td>` + dat["success"][mater]["work_state"] + `</td>`
            if (dat["success"][mater]["work_type"] === "维修工单") {
                html += `<td style="color: #FF5722">` + dat["success"][mater]["amount"] + `</td>`
            } else {
                html += `<td>---</td>`
            }
            html += `<td>` + dat["success"][mater]["log_num"] + `</td>`
            if (dat["success"][mater]["work_type"] === "维修工单") {
                if (dat["success"][mater]["pay_stat"] === "待付款") {
                    html += `<td><span id="payDetail" onclick="payDetail(this)">支付</span></td>`
                } else {
                    html += `<td><span style="color: #0E76E1" ">已付款</span></td>`
                }
            } else {
                html += `<td><span id="payDetail" onclick="payDetail(this)">---</span></td>`
            }
            html += `</tr>`
        }
        $(".search_exhibit").css("display", "block");
        $(".noneTishi").css("display", "none");
        $(".orderDat > .search_exhibit > #search_scrollTable > div > .tbody > .table_data").empty().append(html);
    } else {
        alert(dat["errMsg"]);
    }
}

// 获取日期
function getNow(s) {
    return s < 10 ? '0' + s: s;
}

// 支付/详情按钮事件
function payDetail(val) {
    $(".myOrder").css("display", "none");
    $(".payPanel").css("display", "block");
    var nowtimes=Math.round(new Date().getTime()/1000);

    var myDate = new Date();
    var year=myDate.getFullYear();        //获取当前年
    var month=myDate.getMonth()+1;   //获取当前月
    var date=myDate.getDate();            //获取当前日
    var h=myDate.getHours();              //获取当前小时数(0-23)
    var m=myDate.getMinutes();          //获取当前分钟数(0-59)
    var s=myDate.getSeconds();

    var now=year+'-'+getNow(month)+"-"+getNow(date)+" "+getNow(h)+':'+getNow(m)+":"+getNow(s);

    $("#orderDate").empty().text("ll"+nowtimes + $(val).parent("td").siblings("td").eq(0).text());
    $("#createDate").empty().text(now);
    $("#goodsName").empty().text($(val).parent("td").siblings("td").eq(1).text());
    $("#gas").empty().text($(val).parent("td").siblings("td").eq(4).text());
}

// 支付方式支付
function payMethod(val) {
    var method = $(val).text();
    var orderNo = $("#orderDate").text();
    var createDate = $("#createDate").text();
    var goods = $("#goodsName").parent("span").text();
    var gas = $("#gas").text();
    switch (method) {
        case "支付宝支付":
            $.ajax({
                type: "GET",
                url: "/alipay",
                dataType: "json",
                data: {
                    "order": orderNo,
                    "create": createDate,
                    "goods": goods,
                    "gas": gas,
                    "url": SourceUrl,
                },
                success: (dat) => {
                    console.log(dat["success"])
                    if (dat["success"] !== "") {
                        window.location.href = dat["success"];
                    } else {
                        $("#errorsTishi").empty().text(dat["errMsg"]).delay(6000).fadeOut();
                    }
                }
            });
            break;
        case "微信支付":

            break;
    }
}

// 支付页面返回按钮
function payReturnBtn() {
    window.location.href = SourceUrl;
}